<template>
  <div id="Content-page">
    <div class="content-main">
      <div class="form-input">
        <el-text tag="b" size="large">商品名称</el-text>
        <el-input
          v-model="goodsTitle"
          placeholder="45字以内的商品名称"
          clearable
        ></el-input>
      </div>
      <div class="form-input">
        <el-text tag="b" size="large">商品类目</el-text>
        <el-select v-model="categoryId" clearable placeholder="选择商品分类">
          <el-option
            v-for="item in categoryOptions"
            :key="item._id"
            :label="item.categoryName"
            :value="item._id"
          />
        </el-select>
      </div>
      <div class="form-input">
        <el-text tag="b" size="large">商品图片</el-text>
        <elUpload @uploadedUrl="onLoadUrl" :imageUrl="goodsImage"></elUpload>
      </div>
      <div class="form-input">
        <el-text tag="b" size="large">商品描述</el-text>
        <el-input
          v-model="goodsDescribe"
          placeholder="请输入商品描述"
          type="textarea"
          rows="4"
        ></el-input>
      </div>
    </div>
    <div class="content-main">
      <el-text tag="b" size="large" class="productSpec">商品规格</el-text>
      <el-radio-group v-model="radio" @change="radioEvent">
        <el-radio :value="1">无规格</el-radio>
        <el-radio :value="2">有规格</el-radio>
      </el-radio-group>
      <el-table :data = "specData" style="width: 600px; margin-top: 10px;">
        <el-table-column label="属性" v-if="radio === 2">
          <template #default="scope">
            <div class="product-price">
              <el-input
                placeholder="请输入属性"
                clearable
                v-model="scope.row.productAttributes"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="售价(元)" :key="2">
          <template #default="scope">
            <div class="product-price">
              <el-input
                placeholder="请输入售价"
                clearable
                type="number"
                min="1"
                v-model="scope.row.productPrice"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="库存" :key="3">
          <template #default="scope">
            <div class="product-price">
              <el-input
                placeholder="请输入库存"
                clearable
                type="number"
                min="1"
                v-model="scope.row.productStock"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="radio === 2" :key="4">
          <template #default="scope">
            <el-button type="warning" size="small" @click="deleteSpecData(scope.$index)">
            删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 创建新规格 -->
      <p class="add-new-attribute" v-if="radio === 2" @click="addNewAttribute">创建新规格</p>
    </div>
    <div class="right-upload-button">
    <el-button id="new-button" class="submit-button" :loading="loadingBtn" @click="submitData">{{
        editSpecificProduct().type === "001" ? "提交" : "修改"
      }}</el-button>
    </div>
    
    
  </div>
</template>

<script setup lang="ts">
import { ref ,onMounted} from "vue";
import { ElMessage } from "element-plus";
import { allcateGoryApi,addGoodsApi } from "@/api/api";
import {nullCheck,validateSpecs} from "@/api/form-check"
import elUpload from "@/components/el-upload.vue";
import type { allcateGoryType,goodsStats } from "@/types/index";
import { editSpecificProduct } from "@/store/index";
import { editProductApi } from "@/api/api";
import { useRouter } from "vue-router";
const $router = useRouter()
const goodsTitle = ref("");
const categoryId = ref("");
onMounted(async () => {
  const res = await allcateGoryApi();
  categoryOptions.value = res.data
  if (editSpecificProduct().type === "002") {
    // 编辑商品
    const {
      goods_name,
      category_id,
      goods_describe,
      hasSpecs,
      goods_stats,
      goods_id,
      goods_image,
    } = editSpecificProduct().data;
    console.log(goods_stats);
    goodsTitle.value = goods_name;
    categoryId.value = category_id;
    goodsDescribe.value = goods_describe;
    radio.value = hasSpecs ? 2 : 1;
    specData.value = goods_stats;
    goodsId.value = goods_id;
    goodsImage.value = goods_image;
  }
})
// 商品id：用作编辑商品的参数
const goodsId = ref("");
//储存商品类目
const categoryOptions = ref<allcateGoryType[]>([]);
//商品描述
const goodsDescribe = ref("");

const radio = ref(1);
//规格数据
const specData = ref<goodsStats[]>([
  {
    productAttributes: "",
    productPrice: "",
    productStock: "",
  },
]);
//创建新规格
function addNewAttribute() {
  specData.value.push({
    productAttributes: "",
    productPrice: "",
    productStock: "",
  });
}

function deleteSpecData(index: number) {
  if (specData.value.length < 2) {
    ElMessage({ message: "至少保留一项", duration: 1500 });
    return;
  }
  specData.value.splice(index, 1);
}
// 切换有无规格的时候让specData数据复位
function radioEvent() {
  specData.value = [
    {
      productAttributes: "",
      productPrice: "",
      productStock: "",
    },
  ];
}
const goodsImage = ref("");
// 接收子组件上传的图片链接
function onLoadUrl(url: string) {
  goodsImage.value = url;
}
// 提交
const loadingBtn = ref(false);
async function submitData() {
  // 商品名称
  nullCheck(goodsTitle.value, "请填写商品名称");
  // 商品类目
  nullCheck(categoryId.value, "请选择商品类目");
  // 商品图片
  nullCheck(goodsImage.value, "请上传商品图片");
  // 商品描述
  nullCheck(goodsDescribe.value, "请填写商品描述");
  // 商品规格
  validateSpecs(specData.value, radio.value);
  console.log(specData.value);
  loadingBtn.value = true;
 if (editSpecificProduct().type === "001") {
    try {
      await addGoodsApi({
        category_id: categoryId.value,
        goods_image: goodsImage.value,
        goods_name: goodsTitle.value,
        goods_describe: goodsDescribe.value,
        goods_stats: specData.value,
        hasSpecs: radio.value === 1 ? false : true,
      });
      loadingBtn.value = false;
      $router.push("/dish-list");
    } catch (error) {
      loadingBtn.value = false;
    }
  } else {
    try {
      await editProductApi({
        category_id: categoryId.value,
        goods_image: goodsImage.value,
        goods_name: goodsTitle.value,
        goods_describe: goodsDescribe.value,
        goods_stats: specData.value,
        hasSpecs: radio.value === 1 ? false : true,
        goods_id: goodsId.value,
      });
      loadingBtn.value = false;
      $router.push("/dish-list");
    } catch (error) {
      loadingBtn.value = false;
    }
  }
}
</script>

<style scoped>
.productSpec {
  padding-right: 30px;
}
.right-upload-button {
  text-align: center;
}
.submit-button {
  width: 150px;
}
.product-price {
  display: flex;
  align-items: center;
}
.product-price span {
  width: 50px;
}
.form-input {
  padding-bottom: 15px;
  width: 600px;
}
.form-input >>> .el-text--large {
  display: block;
  margin-bottom: 10px;
}
.content-main .form-input:last-child {
  padding-bottom: 0;
}
.add-new-attribute {
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #576b95;
  cursor: pointer;
  display: inline-block;
  padding-top: 10px;
}
</style>
